//$Id: HibernateSession.java,v 1.1.2.4 2006/12/29 23:25:40 gilmar Exp $
package br.com.cefetrn.apoena.view.component;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Gavin King
 * @author Gilmar P. S. Leitão
 */
public class HibernateSession implements HibernateSessionFactoryAware{
	
	private static final Log LOG = LogFactory.getLog(HibernateSession.class);
	
	private Session session;
	
	private Transaction transaction;
	
	private HibernateSessionFactory factory;
	
	private boolean rollBackOnly;
	
	public Session getSession() throws HibernateException {
		
		LOG.debug("geting Session");
		
		if (session==null){ 
			
			session = factory.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			
		}else{
			
			if(transaction == null)
				transaction = session.beginTransaction();
		}
		//*auto-commit = false
		if(!isActiveTransaction())
			transaction.begin();
		
		return session;
	}
	
	public void setHibernateSessionFactory(HibernateSessionFactory factory) {
		this.factory = factory;
	}
	
	public HibernateSessionFactory getHibernateSessionFactory() {
		
		return factory;
	}

	public void disposeSession() throws HibernateException {
		
		LOG.debug("disposing");

		if (session==null) return;

		if (rollBackOnly) {
			try {
				
				LOG.debug("rolling back");
				
				if (isActiveTransaction())
					transaction.rollback();
			}
			catch (HibernateException e) {
				LOG.error("error during rollback", e);
				throw e;
			}
			finally {
				session.close();
				session=null;
				transaction=null;
			}
		}
		else {
			try {
				
				LOG.debug("committing");
				if (transaction!=null){
						
					if(!isActiveTransaction())
						session.flush();
					else
						if(!transaction.wasCommitted())
							transaction.commit();
					
				}
			}
			catch (HibernateException e) {
				LOG.error("error during commit", e);
				transaction.rollback();
				throw e;
			}
			finally {
				session.close();
				session=null;
				transaction=null;
			}
		}
	}

	public boolean isActiveTransaction(){
		
		if(transaction != null)
			return transaction.isActive();
		else
			return false;
	}
	
	public boolean isRollBackOnly() {
		return rollBackOnly;
	}

	public void setRollBackOnly(boolean rollBackOnly) {
		this.rollBackOnly = rollBackOnly;
	}

}
